package com.atguigu.serviceedu.controller;


import com.atguigu.commonutils.R;
import com.atguigu.serviceedu.client.OrdersClient;
import com.atguigu.serviceedu.entity.*;
import com.atguigu.serviceedu.entity.vo.*;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduCourseService;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.atguigu.serviceedu.service.impl.EduSubjectServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author gengky
 * @since 2021-09-20
 */
@Api(description="课程管理")
@RestController
@RequestMapping("/eduService/course")
//@CrossOrigin //跨域
public class EduCourseController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private EduSubjectService eduSubjectService;

    @Autowired
    OrdersClient ordersClient;

    @ApiOperation("课程购买量加一")
    @PostMapping("AddCourseBuy/{courseID}")
    public R AddCourseBuy(@PathVariable String courseID){
        EduCourse course = eduCourseService.getById(courseID);
        Long buycount = course.getBuyCount()+1;
        course.setBuyCount(buycount);
        eduCourseService.updateById(course);
        return R.ok();
    }

    @ApiOperation("课程点击量加一")
    @PostMapping("AddCoursePoint/{courseID}")
    public R AddCoursePoint(@PathVariable String courseID){
        EduCourse course = eduCourseService.getById(courseID);
        Long viewCount = course.getViewCount()+1;
        course.setViewCount(viewCount);
        eduCourseService.updateById(course);
        return R.ok();
    }


    @ApiOperation("#查询课程订单并绘制表格（总收入）")
    @GetMapping("getCourseOrderCharts2/{begin}/{end}")
    public R getCourseOrderCharts2(@PathVariable(required = false) String begin,
                                  @PathVariable(required = false) String end) {
        if (StringUtils.isEmpty(begin) || "null".equals(begin) || "undefined".equals(begin)){
            begin="2000-01-01";
        }
        if (StringUtils.isEmpty(end) || "null".equals(end) || "undefined".equals(end) ){
            end="2030-01-01";
        }
        List<CourseEarnMVo> list=eduCourseService.getCourseOrderCharts2(begin,end);

        //遍历list1，根据list1中 key 取得 title
        List<CourseBuyChartsVo> list1=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String subjectId = list.get(i).getName();
            String subjectTitle = eduSubjectService.getById(subjectId).getTitle();
            list1.add(new CourseBuyChartsVo(list.get(i).getValue(), subjectTitle));
        }
        System.out.println(list1);

        return R.ok().data("data",list1);
    }


    @ApiOperation("#查询课程订单并绘制表格（购买量）")
    @GetMapping("getCourseBuyCharts2/{begin}/{end}")
    public R getCourseBuyCharts2(@PathVariable(required = false) String begin,
                                   @PathVariable(required = false) String end) {
        if (StringUtils.isEmpty(begin) || "null".equals(begin) || "undefined".equals(begin)){
            begin="2000-01-01";
        }
        if (StringUtils.isEmpty(end) || "null".equals(end) || "undefined".equals(end) ){
            end="2030-01-01";
        }
        List<CourseEarnMVo> list=eduCourseService.getCourseBuyCharts2(begin,end);

        //遍历list1，根据list1中 key 取得 title
        List<CourseBuyChartsVo> list1=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String subjectId = list.get(i).getName();
            String subjectTitle = eduSubjectService.getById(subjectId).getTitle();
            list1.add(new CourseBuyChartsVo(list.get(i).getValue(), subjectTitle));
        }
        System.out.println(list1);

        return R.ok().data("data",list1);
    }

//    @ApiOperation("查询课程订单并绘制表格")
//    @GetMapping("getCourseOrderCharts/{begin}/{end}")
//    public R getCourseOrderCharts(@PathVariable(required = false) String begin,
//                                    @PathVariable(required = false) String end){
//
//        List<Order> list = ordersClient.getCourseOrderChars(begin, end);
//
//        //Map统计数量 *** BigDecimal *** {key:subjectTitle,value:fee}
//        Map<String,BigDecimal> hashmap=new HashMap<>();
//        //根据订单中的 课程ID 获取 课程分类ID
//        for (int i = 0; i < list.size(); i++) {
//            String courseId = list.get(i).getCourseId();
//            EduCourse course = eduCourseService.getById(courseId);
//            EduSubject subject = eduSubjectService.getById(course.getSubjectParentId());
//            String title = subject.getTitle();
//            if (!hashmap.containsKey(title)){
//                hashmap.put(title,list.get(i).getTotalFee());
//            }else {
//                BigDecimal k = hashmap.get(title).add(list.get(i).getTotalFee());
//                hashmap.put(title,k);
//            }
//        }
//        System.out.println(hashmap);
//
//        //遍历Map，根据map的key（即 id）取得 Title
//        List<CourseBuyChartsVo> list1=new ArrayList<>();
//        hashmap.forEach((key,value)->{
////            EduSubject byId = eduSubjectService.getById(key);
//
//            double doubleValue = value.doubleValue();
//            list1.add(new CourseBuyChartsVo(doubleValue,key));
//        });
//        System.out.println(list1.toString());
//
//        return R.ok().data("data",list1);
//
//    }



    @ApiOperation("查询课程分类并绘制表格")
    @GetMapping("getCourseSubjectCharts/{begin}/{end}")
    public R getCourseSubjectCharts(@PathVariable(required = false) String begin,
                                    @PathVariable(required = false) String end){

        QueryWrapper<EduCourse> wrapper=new QueryWrapper<>();

        //查询一定时间范围内
        if (!"null".equals(begin) && !"undefined".equals(begin) && !StringUtils.isEmpty(begin)){
                wrapper.ge("gmt_create",begin);
        }
        if (!"null".equals(end) && !"undefined".equals(begin) && !StringUtils.isEmpty(end)){
                wrapper.le("gmt_create", end);
        }
        List<EduCourse> list = eduCourseService.list(wrapper);

        //Map统计数量
        Map<String, Integer> map=new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            String subjectParentId = list.get(i).getSubjectParentId();
            if (map.get(subjectParentId)==null){
                map.put(subjectParentId,0);
            }else {
                map.put(subjectParentId,map.get(subjectParentId)+1);
            }
        }

        //遍历Map，根据map的key（即 id）取得 Title
        List<CourseSubjectChartsVo> list1=new ArrayList<>();
        map.forEach((key,value)->{
            EduSubject byId = eduSubjectService.getById(key);
            list1.add(new CourseSubjectChartsVo(value,byId.getTitle()));
        });
        System.out.println(list1.toString());

        return R.ok().data("data",list1);

    }

    @ApiOperation(value = "获取课程目录")
    @GetMapping("getCourselistInfo")
    public R getCourselistInfo(){
        List<EduCourse> list = eduCourseService.list(null);
        List<CourseListVo> courseListVos=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            courseListVos.add(new CourseListVo(list.get(i).getTitle(),list.get(i).getId()));
        }
        return R.ok().data("courseinfo",courseListVos);
    }

    @GetMapping("searchCourse/{courseName}")
    public R getCourseByName(@PathVariable("courseName")String courseName){

        Page<EduCourse> eduCoursePage=new Page<>(1,8);

        QueryWrapper<EduCourse> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("title",courseName);


        List<EduCourse> records = eduCourseService.list(queryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", 1);
        map.put("pages", 1);
        map.put("size", records.size());
        map.put("total", records.size());
        map.put("hasNext", false);
        map.put("hasPrevious", false);

        return R.ok().data(map);
    }

    /**
     * 课程列表基本实现
     * @return
     */
    @GetMapping("getCourseList")
    public R getCourseList(){
        List<EduCourse> list = eduCourseService.list(null);
        return R.ok().data("list",list);
    }

    /**
     *
     * @param current
     * @param limit
     * @param courseQuery
     * @return
     */
    @ApiOperation(value = "分页课程列表")
    @PostMapping("PageCondition/{current}/{limit}")
    public R pageTeacherCondition(@PathVariable long current, @PathVariable long limit,
                                  @RequestBody(required = false) CourseQuery courseQuery){
        //创建page对象
        Page<EduCourse> pageCourse=new Page<>(current,limit);
        //构建条件
        QueryWrapper<EduCourse> wrapper=new QueryWrapper<>();

        System.out.println(courseQuery.getTitle());

        //多条件组合查询（动态sql组合）
        if (!StringUtils.isEmpty(courseQuery.getTitle())){
            //构造条件（这里“name”是mysql中的列名，后面一样）
            wrapper.like("title",courseQuery.getTitle());
        }
        if (!StringUtils.isEmpty(courseQuery.getStatus())){
            wrapper.eq("status",courseQuery.getStatus());
        }
        if (!StringUtils.isEmpty(courseQuery.getBegin())){
            wrapper.ge("gmt_create",courseQuery.getBegin());
        }
        if (!StringUtils.isEmpty(courseQuery.getEnd())){
            wrapper.le("gmt_create", courseQuery.getEnd());
        }
        //排序
        wrapper.orderByDesc("gmt_create");
        //调用方法实现条件查询分页
        eduCourseService.page(pageCourse,wrapper);
        //
        List<EduCourse> records = pageCourse.getRecords();

        System.out.println("------分页条件查询课程-------------");
        System.out.println(records.size());

        //
        long total=pageCourse.getTotal();

        return R.ok().data("total",total).data("rows",records);

    }

    /**
     * 删除课程，同时删除课程下的阿里云视频
     * @param courseId
     * @return
     */
    @DeleteMapping("deleteCourseById/{courseId}")
    public R deleteCourseById(@PathVariable String courseId){
        R r = eduCourseService.deleteCourse(courseId);
        return R.ok();
    }




    /**
     * 添加课程信息，涉及 edu_courser 和 edu_course_description
     * @param courseInfoVo
     * @return
     */
    @PostMapping("addCourseInfo")
    public R addCourseInfo(@RequestBody CourseInfoVo courseInfoVo){
        String id=eduCourseService.saveCourseInfo(courseInfoVo);
        return R.ok().data("courseId",id);
    }


    /**
     * 根据课程ID查询课程信息
     * @return
     */
    @GetMapping("getCourseInfoById/{courseId}")
    public R getCourseInfo(@PathVariable String courseId){
        CourseInfoVo courseInfoVo=eduCourseService.getCourseInfoById(courseId);
        return R.ok().data("courseInfoVo",courseInfoVo);
    }

    /**
     * 更新课程信息
     * @return
     */
    @PostMapping("updateCourseInfo")
    public R updateCourseInfo(@RequestBody CourseInfoVo courseInfoVo){
        eduCourseService.updateCourseInfo(courseInfoVo);
        return R.ok();
    }

    /**
     * 根据课程ID查询课程确认信息
     * @return
     */
    @GetMapping("getPublishCourseInfo/{id}")
    public R getPublishCourseInfo(@PathVariable String id){
        CoursePublishVo coursePublishVo=eduCourseService.publishCouseInfo(id);
        return R.ok().data("publishcourse",coursePublishVo);
    }


    /**
     * 最终发布课程，只需要修改课程的状态
     * Normal 已发布，Draft 未发布
     * @return
     */
    @PostMapping("publishCourse/{id}")
    public R publishCourse(@PathVariable String id){
        EduCourse eduCourse=new EduCourse();
        eduCourse.setId(id);
        eduCourse.setStatus("Normal");
        eduCourseService.updateById(eduCourse);
        return R.ok();
    }






}

